/*!
 *  serial.c - H8/300H Tinyサンプルプログラム
 *
 *  日付        内容
 *  ----------- ------------------------------------------------
 *  2009/08/23  新規作成
 */
#include "serial.h"

#include "typedef.h"
#include "36064.h"

#pragma interrupt(intsci3)

volatile BYTE sci_rxrb[SCI_RB_SIZE];
volatile BYTE scicombuff[SCI_RB_SIZE];
BYTE rb_rd_num;
BYTE rb_wr_num;
BYTE scireadcnt;
const BYTE s[16]={"0123456789ABCDEF"};

BYTE intsci3() {
    BYTE temp;
    BYTE next;

    if ((SCI3.SSR.BYTE & 0x18)==0 && SCI3.SSR.BIT.RDRF == 1) {
        next=(rb_wr_num+1)%SCI_RB_SIZE;

        if (rb_rd_num!=next) {
            SCI3.SSR.BYTE &= 0x87;
            sci_rxrb[rb_wr_num] = SCI3.RDR;   //  データを受け取りdataに保存
            rb_wr_num=next;
            return 0;
        }
    }

    temp=SCI3.RDR;
    SCI3.SSR.BYTE &= 0x87;
    return 1;
}


BYTE SciByteRx(BYTE *data) {
    if (rb_rd_num!=rb_wr_num) { //受信バッファ空じゃなかったら
        *data=sci_rxrb[rb_rd_num];
        rb_rd_num=(rb_rd_num+1)%SCI_RB_SIZE;
        return 1;
    } else
        return 0;
}


void InitSci3(BYTE baudrate,BYTE parity ,BYTE stop) {
    UINT dmy;
    BYTE smr = 0;
    scireadcnt=0;

    switch (parity) {
    case even:
        smr = 0x20;
        break;
    case odd:
        smr = 0x30;
        break;
    case non:
    default:
        smr = 0x00;
        break;
    }
    if (stop == 2) {
        smr |= 0x08;
    }

    SCI3.SCR3.BYTE = 0;       //ｼﾘｱﾙｺﾝﾄﾛｰﾙﾚｼﾞｽﾀ(SCIの送信/受信動作設定)
    SCI3.SMR.BYTE = smr;       //ｼﾘｱﾙﾓｰﾄﾞﾚｼﾞｽﾀ(SCIの通信ﾌｫｰﾏｯﾄの設定)
    SCI3.BRR = (BYTE)baudrate;           //1bps

    for (dmy = 280;dmy > 0;dmy--); //Wait 1bit transfer time
    SCI3.SCR3.BYTE = 0x70;    //Enable Tx & Rx ,enable Rx interrupt
    IO.PMR1.BIT.TXD=1;
    SCI3.SSR.BYTE &= 0x80;   //Clear receive error flag
}

void SciByteTx(BYTE data) {

    SCI3.SCR3.BIT.TE=1;
    while (SCI3.SSR.BIT.TDRE!=1);

    SCI3.TDR=data;

    while (SCI3.SSR.BIT.TEND!=1);
    SCI3.SCR3.BIT.TE=0;
}


void SciStrTx(BYTE *str,UINT dataleng) {
    UINT i;

    SCI3.SCR3.BIT.TE=1;

    for (i=0;i<dataleng;i++)
        SciByteTx(str[i]);
}
